<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/29
 * Time: 17:04
 */

namespace Common\Model;

class Auth
{
    /**
     * 退出登录
     */
    public static function logout()
    {
        if (self::check()) {
            session_destroy();
            return true;
        }
        return false;
    }

    /**
     * 获取用户ID
     *
     * @return integer
     */
    public static function id()
    {
        if (self::check()) {
            $user = self::user();
            return $user->id;
        }
        return null;
    }

    /**
     * 检查是否登录
     *
     * @return bool
     */
    public static function check()
    {
        if (isset($_SESSION['users'])) {
            return true;
        }
        return false;
    }

    /**
     * 登录用户
     *
     * @param $email
     * @param $password
     * @return bool|string
     */
    public static function login($email, $password)
    {
        $model = M('users');
        $user = $model->where("email = '{$email}'")->find();

        if (!empty($user) && password_verify($password, $user['password'])) {
            if ($user['ban_time'] != 0) {
                return '此账号已被禁止登陆了';
            }
            self::setUser($user);
            return true;
        } else {
            return '用户名或密码错误';
        }
    }

    /**
     * 更新用户信息
     */
    public static function updateUser() {
        if (self::check()) {
            $user = self::user();
            $model = M('users');
            $user = $model->where('id = ' . $user->id)->find();
            if (empty($user)) {
                self::logout();
            } else {
                if ($user['ban_time'] < 0 || $user['ban_time'] > time()) {
                    self::logout();
                } else {
                    self::setUser($user);
                }
            }
        }
    }

    /**
     * @return User
     */
    public static function user()
    {
        $user = unserialize($_SESSION['users']);
        return $user;
    }

    /**
     * @param array $data
     */
    public static function setUser(array $data) {
        $user = new User();
        $user->setData($data);
        $_SESSION['users'] = serialize($user);
    }
}